<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\User;
use App\Models\Cart;
use App\Models\Shop;
use App\Models\Goods;
use App\Http\Controllers\App\BaseController;

class OrderController extends BaseController
{   
    /**
     * 添加订单
     *
     * @param Request $request
     * @return void
     */
    public function create( Request $request )
    {
        $user_id   = session('user_id');
        
        $cart_id   = $request->input('id');
        $note      = (string)$request->input('note', '');
        $address   = $request->input('address', '');
        $tel       = $request->input('tel', '');
        $name      = $request->input('name', '');
        
        if ( !$note ) {
            $note = '';
        }

        if ( !$name) {
            return self::error('请传递完整的参数');
        }

        $cart_ids  = explode(',', $cart_id);
        
        $user_info = User::find($user_id);
        $shop_id   = empty($user_info['shop_id'])?Shop::where('login', 80000)->value('id') : $user_info['shop_id'];
   
        $order_sn  = $user_id. $shop_id. dechex(time()). rand(1000, 9999);

        $data = Cart::with([
            'norm' => function ( $query ) {
                $query->select('id', 'retail_price', 'name');
            },
            'goods' => function ( $query ) {
                $query->select('id', 'name', 'is_rebate', 'profit');
            }
        ])->where('status', 0)->where('user_id', $user_id)->whereIn('id', $cart_ids)->get()->toArray();
       
        if ( !$data ) {
            return self::error('暂无该商品');
        }
       
        // 订单利润
        $profit_price = 0;
        // 实际支付金额
        $total_amount  = 0;
        // 返利金额
        $rebate_amount = 0;
        // 是否返利订单
        $is_rebate     = 0;
        // 商品件数
        $num = 0;

        foreach ($data as $k => $v) {
            $profit_price += $v['num'] * $v['norm']['retail_price'] * $v['goods']['profit'] / 100;

            $total_amount += $v['num'] * $v['norm']['retail_price'];

            if ( $v['goods']['is_rebate'] == 1) {
                $rebate_amount += $v['num'] * $v['norm']['retail_price'] * $v['goods']['profit'] / 100;
            }

            $num += $v['num'];

            // 修改商品的销量和库存量
            $good_info        = Goods::find($v['goods_id']);
            $good_info->num   = $good_info->num - $v['num'];
            $good_info->sales = $good_info->sales + $v['num'];
            $good_info->save();

            $order_goods[] = new OrderGoods([
                'order_sn'   => $order_sn,
                'goods_id'   => $v['goods_id'],
                'goods_name' => $v['goods']['name'],
                'goods_norm' => $v['norm']['name'],
                'num'        => $v['num'],
                'price'      => $v['norm']['retail_price'],
            ]);
        }

        if ( $rebate_amount ) {
            $is_rebate = 1;
        }

        $info = Order::create([
            'user_id'       => $user_id, 
            'shop_id'       => $shop_id, 
            'order_sn'      => $order_sn, 
            'total_amount'  => $total_amount,
            'receiver'      => $name,
            'tel'           => $tel,
            'address'       => $address,
            'pay_amount'    => $total_amount, 
            'rebate_amount' => $rebate_amount, 
            'rebate_amount' => $rebate_amount, 
            'is_rebate'     => $is_rebate, 
            'note'          => $note,
            'num'           => $num,
            'profit_price'  => $profit_price,
        ]);

        Cart::whereIn('id', $cart_ids)->update([
            'status'     => 1,
            'updated_at' => date('Y-m-d H:i:s', time()),
        ]);

        $info->order_goods()->saveMany($order_goods);

        return self::json(['order' => $order_sn, 'pay_amount' => (string)$total_amount, 'time' => (string)3600*24]);
    }

    /**
     * 展示订单
     *
     * @return void
     */
    public function show( Request $request )
    {
        $status  = $request->input('status', null);
        $user_id = session('user_id');
    
        Order::where('created_at', '<', date('Y-m-d H:i:s', time()-86400) )->where('status', 0)->delete();

        $query = Order::where('user_id', '=', $user_id);
        // 订单的查询条件
        if ( $status !== null ) {

            switch ($status) {
                case 0:
                    $type = [0];
                    break;

                case 1:
                    $type = [1, 2];
                    break;

                case 3:
                    $type = [3];
                    break;
                
                default:
                    return self::error('请传递正确的状态');
                    break;
            }
            
            $query->whereIn('wd_order.status', $type);
        }
        
        $data = $query->with(['order_goods' => function ( $query ) {
                    $query->select('goods_name', 'goods_norm', 'price', 'num', 'order_id', 'goods_id');
                }])
                ->select('id', 'created_at', 'status', 'total_amount', 'num', 'rebate_amount', 'order_sn', 'return_amount', 'is_schedule', 'is_rebate' )
                ->orderBy('id', 'desc')
                ->paginate(10)->toArray();

        $rebate_id = Order::where('user_id', '=', $user_id)->where('status', 3)->where('is_schedule', 0)->value('id');

        $return_data = Order::get_pic($data, $rebate_id);
    
        $return_data = self::pageData($return_data, 'order');
       
        return self::json($return_data);

    }

    /**
     * 订单详情
     *
     * @param Request $request
     * @return void
     */
    public function orderShow( Request $request )
    {
        $id      = $request->input('id');
       
        $user_id = session('user_id');
     
        $query   = Order::where([
                    ['user_id', '=', $user_id],
                    ['id', '=', $id],
        ]);
    
        $data = $query->with(['order_goods' => function ( $query ) {
                    $query->select('goods_name', 'goods_norm', 'price', 'num', 'order_id', 'goods_id', 'created_at');
                }])
                ->first();

        $data->time = ( string)(24*3600 - (time() - $data->created_at->timestamp))  ;

        $shop_info = Shop::select('phone', 'shopname')->find($data['shop_id']);

        foreach ($data['order_goods'] as $k => &$v) {
                
                $v['good_pic'] = Goods::where('id', $v['goods_id'])->value('pic');
               
            }
      
        $data =array_merge($data->toArray(), $shop_info?$shop_info->toArray():[]);
        return self::json($data);
    }

    /**
     * 订单收益
     *
     * @return void
     */
    public function income( Request $request )
    {
        $user_id = session('user_id');

        $data = Order::where('user_id', $user_id)->orderBy('id', 'desc')->select('id', 'order_sn', 'created_at', 'return_amount')->where('return_amount', '>', 0)->paginate(10)->toArray();

        $money = Order::where('user_id', $user_id)->where('return_amount', '>', 0)->sum('return_amount');
        
        $data = self::pageData($data, 'income');
      
        return self::json(['info' => $data, 'money' => $money]);
    }

    /**
     * 立即购买
     *
     * @return void
     */
    public function goodOrder( Request $request )
    {
        $user_id   = session('user_id');
        
        $goods_id  = $request->input('id');
        $norm_id   = $request->input('norm_id');
        $note      = $request->input('note', '');
        $address   = $request->input('address', '');
        $tel       = $request->input('tel', '');
        $name      = $request->input('name', '');
        $num       = $request->input('num', 1);

        $user_info = User ::find($user_id);
        $shop_id   = $user_info['shop_id'];

        $order_sn  = $user_id. $shop_id. dechex(time()). rand(1000, 9999);
        
        if ( !$note ) {
            $note = '';
        }
        $info      = Goods::with(['norm' => function ( $query ) use ( $norm_id ) {
            $query->find($norm_id);
        }])->find($goods_id);
       
        if ( !$info ) {
            return self::error('暂无该商品');
        }
       
        // 订单利润
        $profit_price = 0;
        // 实际支付金额
        $total_amount  = 0;
        // 返利金额
        $rebate_amount = 0;
        // 是否返利订单
        $is_rebate     = 0;
        // 商品件数
      

        $profit_price += $num * $info['norm'][0]['retail_price'] * $info['profit'] / 100;

        $total_amount += $num * $info['norm'][0]['retail_price'];

        if ( $info['is_rebate'] == 1) {
            $rebate_amount += $num * $info['norm'][0]['retail_price'];
        }


        // 修改商品的销量和库存量
       
        $info->num   = $info->num - $num;
        $info->sales = $info->sales + $num;
        $info->save();

        $order_goods = new OrderGoods([
            'order_sn'   => $order_sn,
            'goods_id'   => $goods_id,
            'goods_name' => $info['name'],
            'goods_norm' => $info['norm'][0]['name'],
            'num'        => $num,
            'price'      => $info['norm'][0]['retail_price'],
        ]);
        

        if ( $rebate_amount ) {
            $is_rebate = 1;
        }

        $order_info = Order::create([
            'user_id'       => $user_id, 
            'shop_id'       => $shop_id, 
            'order_sn'      => $order_sn, 
            'total_amount'  => $total_amount,
            'receiver'      => $name,
            'tel'           => $tel,
            'address'       => $address,
            'pay_amount'    => $total_amount, 
            'rebate_amount' => $rebate_amount, 
            'rebate_amount' => $rebate_amount, 
            'is_rebate'     => $is_rebate, 
            'note'          => $note,
            'num'           => $num,
            'profit_price'  => $profit_price,
        ]);

        $order_info->order_goods()->save($order_goods);

        return self::json(['order' => $order_sn, 'pay_amount' => (string)$total_amount, 'time' => (string)3600*24]);
    }

    /**
     * 获取提货码
     *
     * @param Request $request
     * @return void
     */
    public function getcode( Request $request )
    {
        $order_id = $request->input('id');
        $user_id  = session('user_id');
    
        $info = Order::where('id', $order_id)->select('id', 'shop_id', 'code')->whereIn('status', [1, 2])->first();

        if ( !$info ) {
            return self::error('请传递正确的订单');
        }

        $shop_info = Shop::select('shopname', 'latitude', 'longitude')->find( $info['shop_id'] );
        
        $return_data = array_merge($info->toArray(), $shop_info?$shop_info->toArray():[]);
        return self::json($return_data);

    }
}
